3 * Localisation messages cache.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\MediaWikiServices
;
24 use Wikimedia\ScopedCallback
;
25 use MediaWiki\Logger\LoggerFactory
;
26 use Wikimedia\Rdbms\Database
;
29 * MediaWiki message cache structure version.
30 * Bump this whenever the message cache format has changed.
32 define( 'MSG_CACHE_VERSION', 2 );
36 * Performs various MediaWiki namespace-related functions
40 const FOR_UPDATE
= 1; // force message reload
42 /** How long to wait for memcached locks */
44 /** How long memcached locks last */
48 * Process local cache of loaded messages that are defined in
49 * MediaWiki namespace. First array level is a language code,
50 * second level is message key and the values are either message
51 * content prefixed with space, or !NONEXISTENT for negative
58 * @var bool[] Map of (language code => boolean)
60 protected $mCacheVolatile = [];
63 * Should mean that database cannot be used, but check
69 * Lifetime for cache, used by object caching.
70 * Set on construction, see __construct().
75 * Message cache has its own parser which it uses to transform messages
78 protected $mParserOptions;
83 * Variable for tracking which variables are already loaded
84 * @var array $mLoadedLanguages
86 protected $mLoadedLanguages = [];
89 * @var bool $mInParser
91 protected $mInParser = false;
93 /** @var WANObjectCache */
96 protected $clusterCache;
103 * @var MessageCache $instance
105 private static $instance;
108 * Get the signleton instance of this class
111 * @return MessageCache
113 public static function singleton() {
114 if ( self
::$instance === null ) {
115 global $wgUseDatabaseMessages, $wgMsgCacheExpiry, $wgUseLocalMessageCache;
116 self
::$instance = new self(
117 MediaWikiServices
::getInstance()->getMainWANObjectCache(),
118 wfGetMessageCacheStorage(),
119 $wgUseLocalMessageCache
120 ? MediaWikiServices
::getInstance()->getLocalServerObjectCache()
121 : new EmptyBagOStuff(),
122 $wgUseDatabaseMessages,
127 return self
::$instance;
131 * Destroy the singleton instance
135 public static function destroyInstance() {
136 self
::$instance = null;
140 * Normalize message key input
142 * @param string $key Input message key to be normalized
143 * @return string Normalized message key
145 public static function normalizeKey( $key ) {
148 $lckey = strtr( $key, ' ', '_' );
149 if ( ord( $lckey ) < 128 ) {
150 $lckey[0] = strtolower( $lckey[0] );
152 $lckey = $wgContLang->lcfirst( $lckey );
159 * @param WANObjectCache $wanCache
160 * @param BagOStuff $clusterCache
161 * @param BagOStuff $serverCache
162 * @param bool $useDB Whether to look for message overrides (e.g. MediaWiki: pages)
163 * @param int $expiry Lifetime for cache. @see $mExpiry.
165 public function __construct(
166 WANObjectCache
$wanCache,
167 BagOStuff
$clusterCache,
168 BagOStuff
$serverCache,
172 $this->wanCache
= $wanCache;
173 $this->clusterCache
= $clusterCache;
174 $this->srvCache
= $serverCache;
176 $this->mDisable
= !$useDB;
177 $this->mExpiry
= $expiry;
181 * ParserOptions is lazy initialised.
183 * @return ParserOptions
185 function getParserOptions() {
188 if ( !$this->mParserOptions
) {
189 if ( !$wgUser->isSafeToLoad() ) {
190 // $wgUser isn't unstubbable yet, so don't try to get a
191 // ParserOptions for it. And don't cache this ParserOptions
193 $po = ParserOptions
::newFromAnon();
194 $po->setEditSection( false );
195 $po->setAllowUnsafeRawHtml( false );
199 $this->mParserOptions
= new ParserOptions
;
200 $this->mParserOptions
->setEditSection( false );
201 // Messages may take parameters that could come
202 // from malicious sources. As a precaution, disable
203 // the <html> parser tag when parsing messages.
204 $this->mParserOptions
->setAllowUnsafeRawHtml( false );
207 return $this->mParserOptions
;
211 * Try to load the cache from APC.
213 * @param string $code Optional language code, see documenation of load().
214 * @return array|bool The cache array, or false if not in cache.
216 protected function getLocalCache( $code ) {
217 $cacheKey = $this->srvCache
->makeKey( __CLASS__
, $code );
219 return $this->srvCache
->get( $cacheKey );
223 * Save the cache to APC.
225 * @param string $code
226 * @param array $cache The cache array
228 protected function saveToLocalCache( $code, $cache ) {
229 $cacheKey = $this->srvCache
->makeKey( __CLASS__
, $code );
230 $this->srvCache
->set( $cacheKey, $cache );
234 * Loads messages from caches or from database in this order:
235 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
237 * (3) from the database.
239 * When succesfully loading from (2) or (3), all higher level caches are
240 * updated for the newest version.
242 * Nothing is loaded if member variable mDisable is true, either manually
243 * set by calling code or if message loading fails (is this possible?).
245 * Returns true if cache is already populated or it was succesfully populated,
246 * or false if populating empty cache fails. Also returns true if MessageCache
249 * @param string $code Language to which load messages
250 * @param int $mode Use MessageCache::FOR_UPDATE to skip process cache [optional]
251 * @throws MWException
254 protected function load( $code, $mode = null ) {
255 if ( !is_string( $code ) ) {
256 throw new InvalidArgumentException( "Missing language code" );
259 # Don't do double loading...
260 if ( isset( $this->mLoadedLanguages
[$code] ) && $mode != self
::FOR_UPDATE
) {
264 # 8 lines of code just to say (once) that message cache is disabled
265 if ( $this->mDisable
) {
266 static $shownDisabled = false;
267 if ( !$shownDisabled ) {
268 wfDebug( __METHOD__
. ": disabled\n" );
269 $shownDisabled = true;
275 # Loading code starts
276 $success = false; # Keep track of success
277 $staleCache = false; # a cache array with expired data, or false if none has been loaded
278 $where = []; # Debug info, delayed to avoid spamming debug log too much
280 # Hash of the contents is stored in memcache, to detect if data-center cache
281 # or local cache goes out of date (e.g. due to replace() on some other server)
282 list( $hash, $hashVolatile ) = $this->getValidationHash( $code );
283 $this->mCacheVolatile
[$code] = $hashVolatile;
285 # Try the local cache and check against the cluster hash key...
286 $cache = $this->getLocalCache( $code );
288 $where[] = 'local cache is empty';
289 } elseif ( !isset( $cache['HASH'] ) ||
$cache['HASH'] !== $hash ) {
290 $where[] = 'local cache has the wrong hash';
291 $staleCache = $cache;
292 } elseif ( $this->isCacheExpired( $cache ) ) {
293 $where[] = 'local cache is expired';
294 $staleCache = $cache;
295 } elseif ( $hashVolatile ) {
296 $where[] = 'local cache validation key is expired/volatile';
297 $staleCache = $cache;
299 $where[] = 'got from local cache';
301 $this->mCache
[$code] = $cache;
305 $cacheKey = $this->clusterCache
->makeKey( 'messages', $code ); # Key in memc for messages
306 # Try the global cache. If it is empty, try to acquire a lock. If
307 # the lock can't be acquired, wait for the other thread to finish
308 # and then try the global cache a second time.
309 for ( $failedAttempts = 0; $failedAttempts <= 1; $failedAttempts++
) {
310 if ( $hashVolatile && $staleCache ) {
311 # Do not bother fetching the whole cache blob to avoid I/O.
312 # Instead, just try to get the non-blocking $statusKey lock
313 # below, and use the local stale value if it was not acquired.
314 $where[] = 'global cache is presumed expired';
316 $cache = $this->clusterCache
->get( $cacheKey );
318 $where[] = 'global cache is empty';
319 } elseif ( $this->isCacheExpired( $cache ) ) {
320 $where[] = 'global cache is expired';
321 $staleCache = $cache;
322 } elseif ( $hashVolatile ) {
323 # DB results are replica DB lag prone until the holdoff TTL passes.
324 # By then, updates should be reflected in loadFromDBWithLock().
325 # One thread renerates the cache while others use old values.
326 $where[] = 'global cache is expired/volatile';
327 $staleCache = $cache;
329 $where[] = 'got from global cache';
330 $this->mCache
[$code] = $cache;
331 $this->saveToCaches( $cache, 'local-only', $code );
337 # Done, no need to retry
341 # We need to call loadFromDB. Limit the concurrency to one process.
342 # This prevents the site from going down when the cache expires.
343 # Note that the DB slam protection lock here is non-blocking.
344 $loadStatus = $this->loadFromDBWithLock( $code, $where, $mode );
345 if ( $loadStatus === true ) {
348 } elseif ( $staleCache ) {
349 # Use the stale cache while some other thread constructs the new one
350 $where[] = 'using stale cache';
351 $this->mCache
[$code] = $staleCache;
354 } elseif ( $failedAttempts > 0 ) {
355 # Already blocked once, so avoid another lock/unlock cycle.
356 # This case will typically be hit if memcached is down, or if
357 # loadFromDB() takes longer than LOCK_WAIT.
358 $where[] = "could not acquire status key.";
360 } elseif ( $loadStatus === 'cantacquire' ) {
361 # Wait for the other thread to finish, then retry. Normally,
362 # the memcached get() will then yeild the other thread's result.
363 $where[] = 'waited for other thread to complete';
364 $this->getReentrantScopedLock( $cacheKey );
366 # Disable cache; $loadStatus is 'disabled'
373 $where[] = 'loading FAILED - cache is disabled';
374 $this->mDisable
= true;
375 $this->mCache
= false;
376 wfDebugLog( 'MessageCacheError', __METHOD__
. ": Failed to load $code\n" );
377 # This used to throw an exception, but that led to nasty side effects like
378 # the whole wiki being instantly down if the memcached server died
380 # All good, just record the success
381 $this->mLoadedLanguages
[$code] = true;
384 $info = implode( ', ', $where );
385 wfDebugLog( 'MessageCache', __METHOD__
. ": Loading $code... $info\n" );
391 * @param string $code
392 * @param array &$where List of wfDebug() comments
393 * @param int $mode Use MessageCache::FOR_UPDATE to use DB_MASTER
394 * @return bool|string True on success or one of ("cantacquire", "disabled")
396 protected function loadFromDBWithLock( $code, array &$where, $mode = null ) {
397 # If cache updates on all levels fail, give up on message overrides.
398 # This is to avoid easy site outages; see $saveSuccess comments below.
399 $statusKey = $this->clusterCache
->makeKey( 'messages', $code, 'status' );
400 $status = $this->clusterCache
->get( $statusKey );
401 if ( $status === 'error' ) {
402 $where[] = "could not load; method is still globally disabled";
406 # Now let's regenerate
407 $where[] = 'loading from database';
409 # Lock the cache to prevent conflicting writes.
410 # This lock is non-blocking so stale cache can quickly be used.
411 # Note that load() will call a blocking getReentrantScopedLock()
412 # after this if it really need to wait for any current thread.
413 $cacheKey = $this->clusterCache
->makeKey( 'messages', $code );
414 $scopedLock = $this->getReentrantScopedLock( $cacheKey, 0 );
415 if ( !$scopedLock ) {
416 $where[] = 'could not acquire main lock';
417 return 'cantacquire';
420 $cache = $this->loadFromDB( $code, $mode );
421 $this->mCache
[$code] = $cache;
422 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
424 if ( !$saveSuccess ) {
426 * Cache save has failed.
428 * There are two main scenarios where this could be a problem:
429 * - The cache is more than the maximum size (typically 1MB compressed).
430 * - Memcached has no space remaining in the relevant slab class. This is
431 * unlikely with recent versions of memcached.
433 * Either way, if there is a local cache, nothing bad will happen. If there
434 * is no local cache, disabling the message cache for all requests avoids
435 * incurring a loadFromDB() overhead on every request, and thus saves the
436 * wiki from complete downtime under moderate traffic conditions.
438 if ( $this->srvCache
instanceof EmptyBagOStuff
) {
439 $this->clusterCache
->set( $statusKey, 'error', 60 * 5 );
440 $where[] = 'could not save cache, disabled globally for 5 minutes';
442 $where[] = "could not save global cache";
450 * Loads cacheable messages from the database. Messages bigger than
451 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
452 * on-demand from the database later.
454 * @param string $code Language code
455 * @param int $mode Use MessageCache::FOR_UPDATE to skip process cache
456 * @return array Loaded messages for storing in caches
458 protected function loadFromDB( $code, $mode = null ) {
459 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
461 // (T164666) The query here performs really poorly on WMF's
462 // contributions replicas. We don't have a way to say "any group except
463 // contributions", so for the moment let's specify 'api'.
464 // @todo: Get rid of this hack.
465 $dbr = wfGetDB( ( $mode == self
::FOR_UPDATE
) ? DB_MASTER
: DB_REPLICA
, 'api' );
471 'page_is_redirect' => 0,
472 'page_namespace' => NS_MEDIAWIKI
,
476 if ( $wgAdaptiveMessageCache && $code !== $wgLanguageCode ) {
477 if ( !isset( $this->mCache
[$wgLanguageCode] ) ) {
478 $this->load( $wgLanguageCode );
480 $mostused = array_keys( $this->mCache
[$wgLanguageCode] );
481 foreach ( $mostused as $key => $value ) {
482 $mostused[$key] = "$value/$code";
486 if ( count( $mostused ) ) {
487 $conds['page_title'] = $mostused;
488 } elseif ( $code !== $wgLanguageCode ) {
489 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
491 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
492 # other than language code.
493 $conds[] = 'page_title NOT' .
494 $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
497 # Conditions to fetch oversized pages to ignore them
499 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
501 # Load titles for all oversized pages in the MediaWiki namespace
504 [ 'page_title', 'page_latest' ],
506 __METHOD__
. "($code)-big"
508 foreach ( $res as $row ) {
509 $cache[$row->page_title
] = '!TOO BIG';
510 // At least include revision ID so page changes are reflected in the hash
511 $cache['EXCESSIVE'][$row->page_title
] = $row->page_latest
;
514 # Conditions to load the remaining pages with their contents
515 $smallConds = $conds;
516 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
519 [ 'page', 'revision', 'text' ],
520 [ 'page_title', 'old_id', 'old_text', 'old_flags' ],
522 __METHOD__
. "($code)-small",
525 'revision' => [ 'JOIN', 'page_latest=rev_id' ],
526 'text' => [ 'JOIN', 'rev_text_id=old_id' ],
530 foreach ( $res as $row ) {
531 $text = Revision
::getRevisionText( $row );
532 if ( $text === false ) {
533 // Failed to fetch data; possible ES errors?
534 // Store a marker to fetch on-demand as a workaround...
535 // TODO Use a differnt marker
540 . ": failed to load message page text for {$row->page_title} ($code)"
543 $entry = ' ' . $text;
545 $cache[$row->page_title
] = $entry;
548 $cache['VERSION'] = MSG_CACHE_VERSION
;
551 # Hash for validating local cache (APC). No need to take into account
552 # messages larger than $wgMaxMsgCacheEntrySize, since those are only
553 # stored and fetched from memcache.
554 $cache['HASH'] = md5( serialize( $cache ) );
555 $cache['EXPIRY'] = wfTimestamp( TS_MW
, time() +
$this->mExpiry
);
561 * Updates cache as necessary when message page is changed
563 * @param string $title Message cache key with initial uppercase letter
564 * @param string|bool $text New contents of the page (false if deleted)
566 public function replace( $title, $text ) {
567 global $wgLanguageCode;
569 if ( $this->mDisable
) {
573 list( $msg, $code ) = $this->figureMessage( $title );
574 if ( strpos( $title, '/' ) !== false && $code === $wgLanguageCode ) {
575 // Content language overrides do not use the /<code> suffix
579 // (a) Update the process cache with the new message text
580 if ( $text === false ) {
582 $this->mCache
[$code][$title] = '!NONEXISTENT';
584 // Ignore $wgMaxMsgCacheEntrySize so the process cache is up to date
585 $this->mCache
[$code][$title] = ' ' . $text;
588 // (b) Update the shared caches in a deferred update with a fresh DB snapshot
589 DeferredUpdates
::addCallableUpdate(
590 function () use ( $title, $msg, $code ) {
591 global $wgContLang, $wgMaxMsgCacheEntrySize;
592 // Allow one caller at a time to avoid race conditions
593 $scopedLock = $this->getReentrantScopedLock(
594 $this->clusterCache
->makeKey( 'messages', $code )
596 if ( !$scopedLock ) {
597 LoggerFactory
::getInstance( 'MessageCache' )->error(
598 __METHOD__
. ': could not acquire lock to update {title} ({code})',
599 [ 'title' => $title, 'code' => $code ] );
602 // Load the messages from the master DB to avoid race conditions
603 $cache = $this->loadFromDB( $code, self
::FOR_UPDATE
);
604 $this->mCache
[$code] = $cache;
605 // Load the process cache values and set the per-title cache keys
606 $page = WikiPage
::factory( Title
::makeTitle( NS_MEDIAWIKI
, $title ) );
607 $page->loadPageData( $page::READ_LATEST
);
608 $text = $this->getMessageTextFromContent( $page->getContent() );
609 // Check if an individual cache key should exist and update cache accordingly
610 if ( is_string( $text ) && strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
611 $titleKey = $this->bigMessageCacheKey( $this->mCache
[$code]['HASH'], $title );
612 $this->wanCache
->set( $titleKey, ' ' . $text, $this->mExpiry
);
614 // Mark this cache as definitely being "latest" (non-volatile) so
615 // load() calls do try to refresh the cache with replica DB data
616 $this->mCache
[$code]['LATEST'] = time();
617 // Pre-emptively update the local datacenter cache so things like edit filter and
618 // blacklist changes are reflect immediately, as these often use MediaWiki: pages.
619 // The datacenter handling replace() calls should be the same one handling edits
620 // as they require HTTP POST.
621 $this->saveToCaches( $this->mCache
[$code], 'all', $code );
622 // Release the lock now that the cache is saved
623 ScopedCallback
::consume( $scopedLock );
625 // Relay the purge. Touching this check key expires cache contents
626 // and local cache (APC) validation hash across all datacenters.
627 $this->wanCache
->touchCheckKey( $this->wanCache
->makeKey( 'messages', $code ) );
628 // Also delete cached sidebar... just in case it is affected
629 // @TODO: shouldn't this be $code === $wgLanguageCode?
630 if ( $code === 'en' ) {
631 // Purge all language sidebars, e.g. on ?action=purge to the sidebar messages
632 $codes = array_keys( Language
::fetchLanguageNames() );
634 // Purge only the sidebar for this language
637 foreach ( $codes as $code ) {
638 $this->wanCache
->delete( $this->wanCache
->makeKey( 'sidebar', $code ) );
641 // Purge the message in the message blob store
642 $resourceloader = RequestContext
::getMain()->getOutput()->getResourceLoader();
643 $blobStore = $resourceloader->getMessageBlobStore();
644 $blobStore->updateMessage( $wgContLang->lcfirst( $msg ) );
646 Hooks
::run( 'MessageCacheReplace', [ $title, $text ] );
648 DeferredUpdates
::PRESEND
653 * Is the given cache array expired due to time passing or a version change?
655 * @param array $cache
658 protected function isCacheExpired( $cache ) {
659 if ( !isset( $cache['VERSION'] ) ||
!isset( $cache['EXPIRY'] ) ) {
662 if ( $cache['VERSION'] != MSG_CACHE_VERSION
) {
665 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
673 * Shortcut to update caches.
675 * @param array $cache Cached messages with a version.
676 * @param string $dest Either "local-only" to save to local caches only
677 * or "all" to save to all caches.
678 * @param string|bool $code Language code (default: false)
681 protected function saveToCaches( array $cache, $dest, $code = false ) {
682 if ( $dest === 'all' ) {
683 $cacheKey = $this->clusterCache
->makeKey( 'messages', $code );
684 $success = $this->clusterCache
->set( $cacheKey, $cache );
685 $this->setValidationHash( $code, $cache );
690 $this->saveToLocalCache( $code, $cache );
696 * Get the md5 used to validate the local APC cache
698 * @param string $code
699 * @return array (hash or false, bool expiry/volatility status)
701 protected function getValidationHash( $code ) {
703 $value = $this->wanCache
->get(
704 $this->wanCache
->makeKey( 'messages', $code, 'hash', 'v1' ),
706 [ $this->wanCache
->makeKey( 'messages', $code ) ]
710 $hash = $value['hash'];
711 if ( ( time() - $value['latest'] ) < WANObjectCache
::TTL_MINUTE
) {
712 // Cache was recently updated via replace() and should be up-to-date.
713 // That method is only called in the primary datacenter and uses FOR_UPDATE.
714 // Also, it is unlikely that the current datacenter is *now* secondary one.
717 // See if the "check" key was bumped after the hash was generated
718 $expired = ( $curTTL < 0 );
721 // No hash found at all; cache must regenerate to be safe
726 return [ $hash, $expired ];
730 * Set the md5 used to validate the local disk cache
732 * If $cache has a 'LATEST' UNIX timestamp key, then the hash will not
733 * be treated as "volatile" by getValidationHash() for the next few seconds.
734 * This is triggered when $cache is generated using FOR_UPDATE mode.
736 * @param string $code
737 * @param array $cache Cached messages with a version
739 protected function setValidationHash( $code, array $cache ) {
740 $this->wanCache
->set(
741 $this->wanCache
->makeKey( 'messages', $code, 'hash', 'v1' ),
743 'hash' => $cache['HASH'],
744 'latest' => isset( $cache['LATEST'] ) ?
$cache['LATEST'] : 0
746 WANObjectCache
::TTL_INDEFINITE
751 * @param string $key A language message cache key that stores blobs
752 * @param int $timeout Wait timeout in seconds
753 * @return null|ScopedCallback
755 protected function getReentrantScopedLock( $key, $timeout = self
::WAIT_SEC
) {
756 return $this->clusterCache
->getScopedLock( $key, $timeout, self
::LOCK_TTL
, __METHOD__
);
760 * Get a message from either the content language or the user language.
762 * First, assemble a list of languages to attempt getting the message from. This
763 * chain begins with the requested language and its fallbacks and then continues with
764 * the content language and its fallbacks. For each language in the chain, the following
765 * process will occur (in this order):
766 * 1. If a language-specific override, i.e., [[MW:msg/lang]], is available, use that.
767 * Note: for the content language, there is no /lang subpage.
768 * 2. Fetch from the static CDB cache.
769 * 3. If available, check the database for fallback language overrides.
771 * This process provides a number of guarantees. When changing this code, make sure all
772 * of these guarantees are preserved.
773 * * If the requested language is *not* the content language, then the CDB cache for that
774 * specific language will take precedence over the root database page ([[MW:msg]]).
775 * * Fallbacks will be just that: fallbacks. A fallback language will never be reached if
776 * the message is available *anywhere* in the language for which it is a fallback.
778 * @param string $key The message key
779 * @param bool $useDB If true, look for the message in the DB, false
780 * to use only the compiled l10n cache.
781 * @param bool|string|object $langcode Code of the language to get the message for.
782 * - If string and a valid code, will create a standard language object
783 * - If string but not a valid code, will create a basic language object
784 * - If boolean and false, create object from the current users language
785 * - If boolean and true, create object from the wikis content language
786 * - If language object, use it as given
787 * @param bool $isFullKey Specifies whether $key is a two part key "msg/lang".
789 * @throws MWException When given an invalid key
790 * @return string|bool False if the message doesn't exist, otherwise the
791 * message (which can be empty)
793 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
794 if ( is_int( $key ) ) {
795 // Fix numerical strings that somehow become ints
798 } elseif ( !is_string( $key ) ) {
799 throw new MWException( 'Non-string key given' );
800 } elseif ( $key === '' ) {
801 // Shortcut: the empty key is always missing
805 // For full keys, get the language code from the key
806 $pos = strrpos( $key, '/' );
807 if ( $isFullKey && $pos !== false ) {
808 $langcode = substr( $key, $pos +
1 );
809 $key = substr( $key, 0, $pos );
812 // Normalise title-case input (with some inlining)
813 $lckey = self
::normalizeKey( $key );
815 Hooks
::run( 'MessageCache::get', [ &$lckey ] );
817 // Loop through each language in the fallback list until we find something useful
818 $lang = wfGetLangObj( $langcode );
819 $message = $this->getMessageFromFallbackChain(
822 !$this->mDisable
&& $useDB
825 // If we still have no message, maybe the key was in fact a full key so try that
826 if ( $message === false ) {
827 $parts = explode( '/', $lckey );
828 // We may get calls for things that are http-urls from sidebar
829 // Let's not load nonexistent languages for those
830 // They usually have more than one slash.
831 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
832 $message = Language
::getMessageFor( $parts[0], $parts[1] );
833 if ( $message === null ) {
839 // Post-processing if the message exists
840 if ( $message !== false ) {
842 $message = str_replace(
844 # Fix for trailing whitespace, removed by textarea
846 # Fix for NBSP, converted to space by firefox
865 * Given a language, try and fetch messages from that language.
867 * Will also consider fallbacks of that language, the site language, and fallbacks for
870 * @see MessageCache::get
871 * @param Language|StubObject $lang Preferred language
872 * @param string $lckey Lowercase key for the message (as for localisation cache)
873 * @param bool $useDB Whether to include messages from the wiki database
874 * @return string|bool The message, or false if not found
876 protected function getMessageFromFallbackChain( $lang, $lckey, $useDB ) {
881 // First try the requested language.
882 $message = $this->getMessageForLang( $lang, $lckey, $useDB, $alreadyTried );
883 if ( $message !== false ) {
887 // Now try checking the site language.
888 $message = $this->getMessageForLang( $wgContLang, $lckey, $useDB, $alreadyTried );
893 * Given a language, try and fetch messages from that language and its fallbacks.
895 * @see MessageCache::get
896 * @param Language|StubObject $lang Preferred language
897 * @param string $lckey Lowercase key for the message (as for localisation cache)
898 * @param bool $useDB Whether to include messages from the wiki database
899 * @param bool[] $alreadyTried Contains true for each language that has been tried already
900 * @return string|bool The message, or false if not found
902 private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) {
905 $langcode = $lang->getCode();
907 // Try checking the database for the requested language
909 $uckey = $wgContLang->ucfirst( $lckey );
911 if ( !isset( $alreadyTried[ $langcode ] ) ) {
912 $message = $this->getMsgFromNamespace(
913 $this->getMessagePageName( $langcode, $uckey ),
917 if ( $message !== false ) {
920 $alreadyTried[ $langcode ] = true;
926 // Check the CDB cache
927 $message = $lang->getMessage( $lckey );
928 if ( $message !== null ) {
932 // Try checking the database for all of the fallback languages
934 $fallbackChain = Language
::getFallbacksFor( $langcode );
936 foreach ( $fallbackChain as $code ) {
937 if ( isset( $alreadyTried[ $code ] ) ) {
941 $message = $this->getMsgFromNamespace(
942 $this->getMessagePageName( $code, $uckey ), $code );
944 if ( $message !== false ) {
947 $alreadyTried[ $code ] = true;
955 * Get the message page name for a given language
957 * @param string $langcode
958 * @param string $uckey Uppercase key for the message
959 * @return string The page name
961 private function getMessagePageName( $langcode, $uckey ) {
962 global $wgLanguageCode;
964 if ( $langcode === $wgLanguageCode ) {
965 // Messages created in the content language will not have the /lang extension
968 return "$uckey/$langcode";
973 * Get a message from the MediaWiki namespace, with caching. The key must
974 * first be converted to two-part lang/msg form if necessary.
976 * Unlike self::get(), this function doesn't resolve fallback chains, and
977 * some callers require this behavior. LanguageConverter::parseCachedTable()
978 * and self::get() are some examples in core.
980 * @param string $title Message cache key with initial uppercase letter
981 * @param string $code Code denoting the language to try
982 * @return string|bool The message, or false if it does not exist or on error
984 public function getMsgFromNamespace( $title, $code ) {
985 $this->load( $code );
987 if ( isset( $this->mCache
[$code][$title] ) ) {
988 $entry = $this->mCache
[$code][$title];
989 if ( substr( $entry, 0, 1 ) === ' ' ) {
990 // The message exists, so make sure a string is returned.
991 return (string)substr( $entry, 1 );
992 } elseif ( $entry === '!NONEXISTENT' ) {
994 } elseif ( $entry === '!TOO BIG' ) {
995 // Fall through and try invididual message cache below
998 // XXX: This is not cached in process cache, should it?
1000 Hooks
::run( 'MessagesPreLoad', [ $title, &$message, $code ] );
1001 if ( $message !== false ) {
1008 // Individual message cache key
1009 $titleKey = $this->bigMessageCacheKey( $this->mCache
[$code]['HASH'], $title );
1011 if ( $this->mCacheVolatile
[$code] ) {
1013 // Make sure that individual keys respect the WAN cache holdoff period too
1014 LoggerFactory
::getInstance( 'MessageCache' )->debug(
1015 __METHOD__
. ': loading volatile key \'{titleKey}\'',
1016 [ 'titleKey' => $titleKey, 'code' => $code ] );
1018 // Try the individual message cache
1019 $entry = $this->wanCache
->get( $titleKey );
1022 if ( $entry !== false ) {
1023 if ( substr( $entry, 0, 1 ) === ' ' ) {
1024 $this->mCache
[$code][$title] = $entry;
1025 // The message exists, so make sure a string is returned
1026 return (string)substr( $entry, 1 );
1027 } elseif ( $entry === '!NONEXISTENT' ) {
1028 $this->mCache
[$code][$title] = '!NONEXISTENT';
1032 // Corrupt/obsolete entry, delete it
1033 $this->wanCache
->delete( $titleKey );
1037 // Try loading the message from the database
1038 $dbr = wfGetDB( DB_REPLICA
);
1039 $cacheOpts = Database
::getCacheSetOptions( $dbr );
1040 // Use newKnownCurrent() to avoid querying revision/user tables
1041 $titleObj = Title
::makeTitle( NS_MEDIAWIKI
, $title );
1042 if ( $titleObj->getLatestRevID() ) {
1043 $revision = Revision
::newKnownCurrent(
1052 $content = $revision->getContent();
1054 $message = $this->getMessageTextFromContent( $content );
1055 if ( is_string( $message ) ) {
1056 $this->mCache
[$code][$title] = ' ' . $message;
1057 $this->wanCache
->set( $titleKey, ' ' . $message, $this->mExpiry
, $cacheOpts );
1060 // A possibly temporary loading failure
1061 LoggerFactory
::getInstance( 'MessageCache' )->warning(
1062 __METHOD__
. ': failed to load message page text for \'{titleKey}\'',
1063 [ 'titleKey' => $titleKey, 'code' => $code ] );
1064 $message = null; // no negative caching
1067 $message = false; // negative caching
1070 if ( $message === false ) {
1071 // Negative caching in case a "too big" message is no longer available (deleted)
1072 $this->mCache
[$code][$title] = '!NONEXISTENT';
1073 $this->wanCache
->set( $titleKey, '!NONEXISTENT', $this->mExpiry
, $cacheOpts );
1080 * @param string $message
1081 * @param bool $interface
1082 * @param string $language Language code
1083 * @param Title $title
1086 function transform( $message, $interface = false, $language = null, $title = null ) {
1087 // Avoid creating parser if nothing to transform
1088 if ( strpos( $message, '{{' ) === false ) {
1092 if ( $this->mInParser
) {
1096 $parser = $this->getParser();
1098 $popts = $this->getParserOptions();
1099 $popts->setInterfaceMessage( $interface );
1100 $popts->setTargetLanguage( $language );
1102 $userlang = $popts->setUserLang( $language );
1103 $this->mInParser
= true;
1104 $message = $parser->transformMsg( $message, $popts, $title );
1105 $this->mInParser
= false;
1106 $popts->setUserLang( $userlang );
1115 function getParser() {
1116 global $wgParser, $wgParserConf;
1118 if ( !$this->mParser
&& isset( $wgParser ) ) {
1119 # Do some initialisation so that we don't have to do it twice
1120 $wgParser->firstCallInit();
1121 # Clone it and store it
1122 $class = $wgParserConf['class'];
1123 if ( $class == ParserDiffTest
::class ) {
1125 $this->mParser
= new $class( $wgParserConf );
1127 $this->mParser
= clone $wgParser;
1131 return $this->mParser
;
1135 * @param string $text
1136 * @param Title $title
1137 * @param bool $linestart Whether or not this is at the start of a line
1138 * @param bool $interface Whether this is an interface message
1139 * @param Language|string $language Language code
1140 * @return ParserOutput|string
1142 public function parse( $text, $title = null, $linestart = true,
1143 $interface = false, $language = null
1147 if ( $this->mInParser
) {
1148 return htmlspecialchars( $text );
1151 $parser = $this->getParser();
1152 $popts = $this->getParserOptions();
1153 $popts->setInterfaceMessage( $interface );
1155 if ( is_string( $language ) ) {
1156 $language = Language
::factory( $language );
1158 $popts->setTargetLanguage( $language );
1160 if ( !$title ||
!$title instanceof Title
) {
1161 wfDebugLog( 'GlobalTitleFail', __METHOD__
. ' called by ' .
1162 wfGetAllCallers( 6 ) . ' with no title set.' );
1165 // Sometimes $wgTitle isn't set either...
1167 # It's not uncommon having a null $wgTitle in scripts. See r80898
1168 # Create a ghost title in such case
1169 $title = Title
::makeTitle( NS_SPECIAL
, 'Badtitle/title not set in ' . __METHOD__
);
1172 $this->mInParser
= true;
1173 $res = $parser->parse( $text, $title, $popts, $linestart );
1174 $this->mInParser
= false;
1179 function disable() {
1180 $this->mDisable
= true;
1184 $this->mDisable
= false;
1188 * Whether DB/cache usage is disabled for determining messages
1190 * If so, this typically indicates either:
1191 * - a) load() failed to find a cached copy nor query the DB
1192 * - b) we are in a special context or error mode that cannot use the DB
1193 * If the DB is ignored, any derived HTML output or cached objects may be wrong.
1194 * To avoid long-term cache pollution, TTLs can be adjusted accordingly.
1199 public function isDisabled() {
1200 return $this->mDisable
;
1204 * Clear all stored messages. Mainly used after a mass rebuild.
1207 $langs = Language
::fetchLanguageNames( null, 'mw' );
1208 foreach ( array_keys( $langs ) as $code ) {
1209 # Global and local caches
1210 $this->wanCache
->touchCheckKey( $this->wanCache
->makeKey( 'messages', $code ) );
1213 $this->mLoadedLanguages
= [];
1217 * @param string $key
1220 public function figureMessage( $key ) {
1221 global $wgLanguageCode;
1223 $pieces = explode( '/', $key );
1224 if ( count( $pieces ) < 2 ) {
1225 return [ $key, $wgLanguageCode ];
1228 $lang = array_pop( $pieces );
1229 if ( !Language
::fetchLanguageName( $lang, null, 'mw' ) ) {
1230 return [ $key, $wgLanguageCode ];
1233 $message = implode( '/', $pieces );
1235 return [ $message, $lang ];
1239 * Get all message keys stored in the message cache for a given language.
1240 * If $code is the content language code, this will return all message keys
1241 * for which MediaWiki:msgkey exists. If $code is another language code, this
1242 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
1243 * @param string $code Language code
1244 * @return array Array of message keys (strings)
1246 public function getAllMessageKeys( $code ) {
1249 $this->load( $code );
1250 if ( !isset( $this->mCache
[$code] ) ) {
1251 // Apparently load() failed
1254 // Remove administrative keys
1255 $cache = $this->mCache
[$code];
1256 unset( $cache['VERSION'] );
1257 unset( $cache['EXPIRY'] );
1258 unset( $cache['EXCESSIVE'] );
1259 // Remove any !NONEXISTENT keys
1260 $cache = array_diff( $cache, [ '!NONEXISTENT' ] );
1262 // Keys may appear with a capital first letter. lcfirst them.
1263 return array_map( [ $wgContLang, 'lcfirst' ], array_keys( $cache ) );
1267 * Purge message caches when a MediaWiki: page is created, updated, or deleted
1269 * @param Title $title Message page title
1270 * @param Content|null $content New content for edit/create, null on deletion
1273 public function updateMessageOverride( Title
$title, Content
$content = null ) {
1276 $msgText = $this->getMessageTextFromContent( $content );
1277 if ( $msgText === null ) {
1278 $msgText = false; // treat as not existing
1281 $this->replace( $title->getDBkey(), $msgText );
1283 if ( $wgContLang->hasVariants() ) {
1284 $wgContLang->updateConversionTable( $title );
1289 * @param Content|null $content Content or null if the message page does not exist
1290 * @return string|bool|null Returns false if $content is null and null on error
1292 private function getMessageTextFromContent( Content
$content = null ) {
1293 // @TODO: could skip pseudo-messages like js/css here, based on content model
1295 // Message page exists...
1296 // XXX: Is this the right way to turn a Content object into a message?
1297 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
1298 // CssContent. MessageContent is *not* used for storing messages, it's
1299 // only used for wrapping them when needed.
1300 $msgText = $content->getWikitextForTransclusion();
1301 if ( $msgText === false ||
$msgText === null ) {
1302 // This might be due to some kind of misconfiguration...
1304 LoggerFactory
::getInstance( 'MessageCache' )->warning(
1305 __METHOD__
. ": message content doesn't provide wikitext "
1306 . "(content model: " . $content->getModel() . ")" );
1309 // Message page does not exist...
1317 * @param string $hash Hash for this version of the entire key/value overrides map
1318 * @param string $title Message cache key with initial uppercase letter
1321 private function bigMessageCacheKey( $hash, $title ) {
1322 return $this->wanCache
->makeKey( 'messages-big', $hash, $title );